//
//  VEAssiciationDongtaiViewController.m
//  VEMoneyPorject
//
//  Created by BlueWind on 2018/9/13.
//  Copyright © 2018年 陈建. All rights reserved.
//

#import "VEAssiciationDongtaiViewController.h"

#import "VERemondHeadTableViewCell.h"
#import "VERemondCommentTableViewCell.h"
#import "VERemondContentTableViewCell.h"

#import "RemondTableViewCell.h"

#import "VERemondDetailViewController.h"
#import "MainLiveInPutTollBarAlertSendInfoView.h"
#import "DTLogInViewController.h"

@interface VEAssiciationDongtaiViewController ()

@end

@implementation VEAssiciationDongtaiViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.isSuccessNet = YES;
    
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, -20, 0);
    // 可以刷新可以加载更多
    self.refreshType = CJBaseTableVcRefreshTypeRefreshAndLoadMore;
    [self cj_refresh];
}


- (void)cj_refresh{
    [super cj_refresh];
    [self loadData];
}

- (void)loadData{
    [super loadData];
    [self requestDataWithType:1];
    
}

- (void)cj_loadMore{
    [super cj_loadMore];
    NSLog(@"%ld",self.page);
    [self requestDataWithType:2];
    
}

- (void)requestDataWithType:(NSInteger)type{
    
    NSString *url = [NSString stringWithFormat:@"%@/VEService/GetSQDongtai.do",kPublicInterfaceAPI];
    CJBaseRequest *request = [CJBaseRequest cj_requestWithUrl:url isPost:YES withParameters:@{@"shequnid":self.assionId,@"Page":@(self.page)}];
    [request cj_sendRequestWithCompletion:^(id response, BOOL success, NSString *message) {
        self.isSuccessNet = YES;
        [self cj_endRefresh];
        [self cj_endLoadMore];
        if (![NSObject isNilOrNull:response]) {
            NSArray *arr = response;
            if (arr.count == 0) {
                self.page -=1;
                return;
            }
            if (type == 1) {
                [self.dataArray removeAllObjects];
                self.dataArray = [VERemondModel mj_objectArrayWithKeyValuesArray:arr];
            } else {
                NSArray *arr1 = [VERemondModel mj_objectArrayWithKeyValuesArray:arr];
                [self.dataArray addObjectsFromArray:arr1];
            }
            
            
            [self.tableView reloadData];
        }
    }];
}

- (NSInteger)cj_numberOfSections {
    return self.dataArray.count;
}

/**
 某个cell的数量
 */
- (NSInteger)cj_numberOfRowsInsection:(NSInteger)section {
    NSArray *arr = [NSArray new];
    
    if (self.dataArray.count > 0) {
        VERemondModel *model = self.dataArray[section];
        arr = [model.PINGLUN componentsSeparatedByString:@"&&"];
        
    }
    return 2 + arr.count;
}

- (CGFloat)cj_cellHeightAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        return 70;
    } else if (indexPath.row == 1) {
        VERemondModel *model = self.dataArray[indexPath.section];
        
        CGFloat allHeight = 76;
        
        CGFloat h = [model.DYNAMICTEXT heigthWithWeight:(SCREEN_WIDTH - 30) andFont:16 andLineSpacing:2 andWordSpacing:1];
        
        if (h > 100) {
            allHeight += 100 + 30;
        } else {
            allHeight += (h + 8);
        }
        
        
        if (model.DYNAMICPHOTO.length != 0) {
            
            NSArray *arr = [model.DYNAMICPHOTO componentsSeparatedByString:@","];
            
            double row = ceil(arr.count/3.0);

            
            allHeight += (((SCREEN_WIDTH - 2 *(GAP15 + GAP8))/3 + 16) + 8 ) * row;
        }
        
        if (model.ZANNAME.length != 0) {
            
            NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:model.ZANNAME];
            //NSTextAttachment可以将要插入的图片作为特殊字符处理
            NSTextAttachment *attch = [[NSTextAttachment alloc] init];
            //定义图片内容及位置和大小
            attch.image = [UIImage imageNamed:@"超级赞"];
            attch.bounds = CGRectMake(0, 0, 14, 14);
            //创建带有图片的富文本
            NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
            //将图片放在第一位
            [attri insertAttributedString:string atIndex:0];
            
            CGFloat height =  [attri boundingRectWithSize:CGSizeMake(SCREEN_WIDTH - 30, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size.height;//针对富文本有专门的计算动态高度的方法，与nsstring 大同小异；
            allHeight += (height + 16);
        }
        
        return allHeight;
        
    } else {
        VERemondModel *model = self.dataArray[indexPath.section];
        NSArray *commentArray = [model.PINGLUN componentsSeparatedByString:@"&&"];
        
        CGFloat h =  [commentArray[indexPath.row - 2] heigthWithWeight:(SCREEN_WIDTH - 30) andFont:16 andLineSpacing:2 andWordSpacing:1];
        return h + 16;
        
    }
    
}

/**
 某行的cell
 */
- (CJBaseTableViewCell *)cj_cellAtIndexPath:(NSIndexPath *)indexPath {
    
    WEAKSELF
    VERemondModel *model = self.dataArray[indexPath.section];
    if (indexPath.row == 0) {
        VERemondHeadTableViewCell *cell = [VERemondHeadTableViewCell cellWithTableView:self.tableView];
        cell.model = model;
        return cell;
    } else if (indexPath.row == 1) {
        RemondTableViewCell *cell = [RemondTableViewCell cellWithTableView:self.tableView];
        cell.isDongtai = YES;
        cell.model = model;

        [cell.summaryLabel setTapActionWithBlock:^{
            VERemondDetailViewController *vc = [VERemondDetailViewController new];
            vc.model = model;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }];
        
        [cell.lookAll setTapActionWithBlock:^{
            VERemondDetailViewController *vc = [VERemondDetailViewController new];
            vc.model = model;
            [weakSelf.navigationController pushViewController:vc animated:YES];
            
        }];
        cell.share = ^{
            
            if (![[CJUserInfoManager sharedManager] isLogin]) {
                DTLogInViewController *vc = [[DTLogInViewController alloc] init];
                vc.loginSuccessBlock = ^{
                };
                [self pushVc:vc];
            } else {
                NSString *url = [NSString stringWithFormat:@"%@/down.html?userid=%@",kPublicInterfaceAPI,[CJUserInfoManager sharedManager].currentUserInfo.USERID];
                [[shareFunctionCJ shareFunction] shareInfoP:self.view viewController:self WithUrlSTr:url WithTitle:@"分享推荐" withImageViewUrlStr:nil withDetailTitleString:nil withType:0];
            }
        };
        
        cell.sendMessage = ^{
            //发送消息
            MainLiveInPutTollBarAlertSendInfoView *view = [[MainLiveInPutTollBarAlertSendInfoView alloc] initWithFrame:CGRectMake(0, 0, weakSelf.view.width, weakSelf.view.height)];
            
            if (![[CJUserInfoManager sharedManager] isLogin]) {
                DTLogInViewController *vc = [[DTLogInViewController alloc] init];
                vc.loginSuccessBlock = ^{
                };
                [self pushVc:vc];
            } else {
                NSString *userId = [[CJUserInfoManager sharedManager] currentUserInfo].USERID;
                view.SendInfoTextBlock = ^(NSString *text) {
                    NSLog(@"发送消息 == %@",text);
                    NSString *url = [NSString stringWithFormat:@"%@/VEService/GetCommentDynamic.do",kPublicInterfaceAPI];
                    
                    NSDictionary *dic = @{
                                          @"Dynamicid": model.DYNAMICID,
                                          @"Userid": userId,
                                          @"Dynamictext": text
                                          };
                    
                    CJBaseRequest *request = [CJBaseRequest cj_requestWithUrl:url isPost:YES withParameters:dic];
                    [request cj_sendRequestWithCompletion:^(id response, BOOL success, NSString *message) {
                        [CJUIKit showSuccessWithStatus:message];
                    }];
                };
                
                [view showInputView];
            }
            
            
        };
        
        cell.clickLike = ^{ // 点赞
            NSString *userId = [[CJUserInfoManager sharedManager] currentUserInfo].USERID;
            
            if (![[CJUserInfoManager sharedManager] isLogin]) {
                
                DTLogInViewController *vc = [[DTLogInViewController alloc] init];
                vc.loginSuccessBlock = ^{
                };
                [self pushVc:vc];
                
                
            } else {
                if ([model.ZANNAME containsString: [[CJUserInfoManager sharedManager] currentUserInfo].USERNAME]) {
                    NSDictionary *dic = @{
                                          @"Userid": userId,
                                          @"Dynamicid": model.DYNAMICID,
                                          };
                    NSString *url = [NSString stringWithFormat:@"%@/VEService/DeleteZAN.do",kPublicInterfaceAPI];
                    CJBaseRequest *request = [CJBaseRequest cj_requestWithUrl:url isPost:YES withParameters:dic];
                    [request cj_sendRequestWithCompletion:^(id response, BOOL success, NSString *message) {
                        
                        [CJUIKit showSuccessWithStatus:message];
                        NSString *name = [[CJUserInfoManager sharedManager] currentUserInfo].USERNAME;
                        model.ZANNAME = [model.ZANNAME stringByReplacingOccurrencesOfString:name withString:@""];
                        //                        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationNone)];
                        [self.tableView reloadData];
                    }];
                } else {
                    NSDictionary *dic = @{
                                          @"Userid": userId,
                                          @"Dynamicid": model.DYNAMICID,
                                          };
                    NSString *url = [NSString stringWithFormat:@"%@/VEService/GetZAN.do",kPublicInterfaceAPI];
                    CJBaseRequest *request = [CJBaseRequest cj_requestWithUrl:url isPost:YES withParameters:dic];
                    [request cj_sendRequestWithCompletion:^(id response, BOOL success, NSString *message) {
                        
                        [CJUIKit showSuccessWithStatus:message];
                        NSString *name = [[CJUserInfoManager sharedManager] currentUserInfo].USERNAME;
                        
                        model.ZANNAME = [model.ZANNAME stringByAppendingString:name];
                        //                        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationNone)];
                        [self.tableView reloadData];
                    }];
                }
                
            }
        };
        cell.clickImage = ^(NSArray *imagesUrl, UIImageView *view) {
            
            NSInteger i = view.tag - 20;
            
            [HUPhotoBrowser showFromImageView:view withURLStrings:imagesUrl atIndex:i];
        };
        return cell;
    } else {
        VERemondCommentTableViewCell *cell = [VERemondCommentTableViewCell cellWithTableView:self.tableView];
        VERemondModel *model = self.dataArray[indexPath.section];
        NSArray *commmentArray = [model.PINGLUN componentsSeparatedByString:@"&&"];
        cell.comment = commmentArray[indexPath.row - 2];
        return cell;
    }
    
}

@end
